package com.xiuxia.bopicturebackend.common;

import net.coobird.thumbnailator.Thumbnails;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageUtils {
    /**
     * 确保图片为 RGB 格式
     */
    public static BufferedImage toRGB(BufferedImage image) {
        if (image.getColorModel().getPixelSize() == 24 &&
                image.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            // 如果是灰度图，转换为 RGB
            BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            rgbImage.getGraphics().drawImage(image, 0, 0, null);
            return rgbImage;
        } else if (image.getType() == BufferedImage.TYPE_CUSTOM) {
            // 如果是自定义类型，也统一转成 RGB
            BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            rgbImage.getGraphics().drawImage(image, 0, 0, null);
            return rgbImage;
        } else if (image.getAlphaRaster() != null) {
            // 如果有透明通道（如 PNG），移除 alpha 通道
            BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            rgbImage.getGraphics().drawImage(image, 0, 0, null);
            return rgbImage;
        }
        return image;
    }

    /**
     * 生成压缩图（保持尺寸不变，降低质量）
     */
    public static byte[] compress(BufferedImage image, String format, float quality) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Thumbnails.of(toRGB(image))
                .scale(1.0)          // 保持原尺寸
                .outputFormat(format)
                .outputQuality(quality)
                .toOutputStream(os);
        return os.toByteArray();
    }

    /**
     * 生成缩略图（调整尺寸）
     */
    public static byte[] resize(BufferedImage image, int width, int height, String format) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Thumbnails.of(image)
                .size(width, height)
                .outputFormat(format)
                .toOutputStream(os);
        return os.toByteArray();
    }
}
